#import "ViewController.h"
#import "GameController.h"
#import <QuartzCore/QuartzCore.h>

extern const NSUInteger kMaxRows;
extern const NSUInteger kMaxCols;
const NSUInteger kNumberOfPictures = 10;

@interface ViewController ()

@property (retain, nonatomic) IBOutletCollection(UIImageView) NSArray* boxImageViews;
@property (weak, nonatomic) IBOutlet UIButton *startGameButton;
@property UIView* gameBoard;
@property GameController* gameController;

@property (weak, nonatomic) IBOutlet UILabel *pointsLabel;

@property   Box* generatedBox;
@end

@implementation ViewController

    //New Game action button
- (IBAction)startNewGameButton:(id)sender {
    [self clearAllBoxes];
    
    [self.gameController generateBoxAtRandomEmptyPlace];
    [self.gameController generateBoxAtRandomEmptyPlace];
    [self refreshBoxes];
    
    [self.gameController removeAllPoints];
    self.pointsLabel.text = @"0";
    
    [self generateRandomBackgroundPicture];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //Points label
    self.pointsLabel.text =[NSString stringWithFormat:@"%ld",[self.gameController points]];
    
    //Game Board options: rounded edges, transparency, etc...
    self.gameBoard = self.view.subviews[0];
    self.gameBoard.layer.cornerRadius = 10;
    self.gameBoard.layer.shadowOffset = CGSizeMake(1, 1);
    self.gameBoard.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.gameBoard.layer.shadowRadius = 10.0f;
    self.gameBoard.layer.shadowOpacity = 0.80f;
    self.gameBoard.layer.shadowPath = [[UIBezierPath bezierPathWithRect:self.gameBoard.layer.bounds] CGPath];
    
    //Setting the swipe gesture recognizers
    
    [self.gameBoard setUserInteractionEnabled:YES];
    
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    UISwipeGestureRecognizer *swipeUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
    
                    // Setting the swipe direction.
    [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
    [swipeUp setDirection:UISwipeGestureRecognizerDirectionUp];
    [swipeDown setDirection:UISwipeGestureRecognizerDirectionDown];
    
                    // Adding the swipe gesture on  view
    [self.gameBoard addGestureRecognizer:swipeLeft];
    [self.gameBoard addGestureRecognizer:swipeRight];
    [self.gameBoard addGestureRecognizer:swipeUp];
    [self.gameBoard addGestureRecognizer:swipeDown];
    
        //Game Board background
    [self generateRandomBackgroundPicture];

        //New Game button options

    [self.startGameButton setImage:[UIImage imageNamed:@"new_game_pressed.png"] forState:UIControlStateHighlighted];


    self.gameController = [GameController sharedGameController];

    
    [self.gameController generateBoxAtRandomEmptyPlace];
    [self.gameController generateBoxAtRandomEmptyPlace];
    
    [self.gameController generateBoxAtRandomEmptyPlace];
    [self.gameController generateBoxAtRandomEmptyPlace];
    
    [self.gameController generateBoxAtRandomEmptyPlace];
    [self.gameController generateBoxAtRandomEmptyPlace];
    
    [self.gameController generateBoxAtRandomEmptyPlace];
    [self.gameController generateBoxAtRandomEmptyPlace];
    
    [self.gameController generateBoxAtRandomEmptyPlace];
    [self.gameController generateBoxAtRandomEmptyPlace];
    
    [self.gameController generateBoxAtRandomEmptyPlace];
    [self.gameController generateBoxAtRandomEmptyPlace];
    
    [self.gameController generateBoxAtRandomEmptyPlace];
    [self.gameController generateBoxAtRandomEmptyPlace];
    
    [self.gameController generateBoxAtRandomEmptyPlace];
    [self.gameController generateBoxAtRandomEmptyPlace];
    

    [self refreshBoxes];
    
    
}

        //Swiping controller
- (void)handleSwipe:(UISwipeGestureRecognizer *)swipe {
      BOOL hasChanged = NO;


    
    if (swipe.direction == UISwipeGestureRecognizerDirectionLeft) {
        NSLog(@"Left Swipe");
        for (NSUInteger indexRow = 0; indexRow < kMaxRows; indexRow++) {
            for (NSUInteger indexCol = 0; indexCol < kMaxCols; indexCol++) {
                [self.gameController.gamePlayground objectAtRow:indexRow column:indexCol].mergedThisRound = NO;
                for (NSUInteger currentCol = indexCol; currentCol > 0; currentCol--) {
                    
                    if ([self.gameController.gamePlayground objectAtRow:indexRow column:currentCol-1]) {
                        
                        if([self.gameController.gamePlayground objectAtRow:indexRow column:currentCol].value == 0){
                            continue;
                        }
                        if ([self.gameController.gamePlayground objectAtRow:indexRow column:currentCol-1].value == [self.gameController.gamePlayground objectAtRow:indexRow column:currentCol].value) {
                            
                            if ([self.gameController.gamePlayground objectAtRow:indexRow column:currentCol-1].mergedThisRound) {
                              hasChanged = YES;
                                break;
                            }
                            Box* temp = [[Box alloc] initWithValue:[self.gameController.gamePlayground objectAtRow:indexRow column:currentCol-1].value*2];
                            
                            //Adding points
                            [self.gameController addPoints:[self.gameController.gamePlayground objectAtRow:indexRow column:currentCol-1].value];
                            
                            [self.gameController.gamePlayground insertObject:temp atRow:indexRow column:currentCol - 1];
                            [self.gameController.gamePlayground insertObject:nil atRow:indexRow column:currentCol];
                            [self.gameController.gamePlayground objectAtRow:indexRow column:currentCol-1].mergedThisRound = YES;
                            break;
                            
                        }
                        else {
                            [self.gameController.gamePlayground objectAtRow:indexRow column:currentCol-1].mergedThisRound = YES;
                            hasChanged =NO;
                        }
                        
                    }
                    else {
                        hasChanged=YES;
                        Box* temp = [[Box alloc] initWithValue:[self.gameController.gamePlayground objectAtRow:indexRow     column:currentCol].value];
                        if(temp.value == 0) {
                            continue;
                        }
                        
                        [self.gameController.gamePlayground insertObject:temp atRow:indexRow column:currentCol - 1];
                        [self.gameController.gamePlayground insertObject:nil atRow:indexRow column:currentCol];
                    }
                }
            }
        }

        if(hasChanged){
            [self.gameController generateBoxAtRandomEmptyPlace];
        }
    }
    if (swipe.direction == UISwipeGestureRecognizerDirectionRight) {
        for (NSUInteger indexRow = 0; indexRow < kMaxRows; indexRow++) {
            for (NSUInteger indexCol = 0; indexCol < kMaxRows; indexCol++) {
                [self.gameController.gamePlayground objectAtRow:indexRow column:indexCol].mergedThisRound = NO;
                for (NSUInteger currentCol = indexCol; currentCol <kMaxCols-1 ; currentCol++) {
                    
                    if ([self.gameController.gamePlayground objectAtRow:indexRow column:currentCol+1]) {
                        
                        if([self.gameController.gamePlayground objectAtRow:indexRow column:currentCol].value == 0){
                            continue;
                        }
                        if ([self.gameController.gamePlayground objectAtRow:indexRow column:currentCol+1].value == [self.gameController.gamePlayground objectAtRow:indexRow column:currentCol].value) {
                            
                            if ([self.gameController.gamePlayground objectAtRow:indexRow column:currentCol+1].mergedThisRound) {
                                hasChanged = YES;
                                break;
                            }
                            Box* temp = [[Box alloc] initWithValue:[self.gameController.gamePlayground objectAtRow:indexRow column:currentCol+1].value*2];
                            //Adding points
                            [self.gameController addPoints:[self.gameController.gamePlayground objectAtRow:indexRow column:currentCol-1].value];
                            [self.gameController.gamePlayground insertObject:temp atRow:indexRow column:currentCol +1];
                            [self.gameController.gamePlayground insertObject:nil atRow:indexRow column:currentCol];
                            [self.gameController.gamePlayground objectAtRow:indexRow column:currentCol+1].mergedThisRound = YES;
                            break;
                            
                        }
                        else {
                            [self.gameController.gamePlayground objectAtRow:indexRow column:currentCol+1].mergedThisRound = YES;
                            hasChanged =NO;
                        }
                        
                    }
                    else {
                        hasChanged=YES;
                        Box* temp = [[Box alloc] initWithValue:[self.gameController.gamePlayground objectAtRow:indexRow     column:currentCol].value];
                        if(temp.value == 0) {
                            continue;
                        }
                        
                        [self.gameController.gamePlayground insertObject:temp atRow:indexRow column:currentCol + 1];
                        [self.gameController.gamePlayground insertObject:nil atRow:indexRow column:currentCol];
                    }
                }
            }
        }
        
        if(hasChanged){
            [self.gameController generateBoxAtRandomEmptyPlace];
        }
    }
    if (swipe.direction == UISwipeGestureRecognizerDirectionUp) {
        for (NSUInteger indexRow = 0; indexRow < kMaxRows; indexRow++) {
            for (NSUInteger indexCol = 0; indexCol < kMaxRows; indexCol++) {
                [self.gameController.gamePlayground objectAtRow:indexRow column:indexCol].mergedThisRound = NO;
                for (NSUInteger currentRow = indexRow; currentRow <kMaxRows ; currentRow--) {
                    
                    if ([self.gameController.gamePlayground objectAtRow:currentRow-1 column:indexCol]) {
                        
                        if([self.gameController.gamePlayground objectAtRow:currentRow column:indexCol].value == 0){
                            continue;
                        }
                        if ([self.gameController.gamePlayground objectAtRow:currentRow-1 column:indexCol].value == [self.gameController.gamePlayground objectAtRow:currentRow column:indexCol].value) {
                            
                            if ([self.gameController.gamePlayground objectAtRow:currentRow-1 column:indexCol].mergedThisRound) {
                                hasChanged = YES;
                                break;
                            }
                            Box* temp = [[Box alloc] initWithValue:[self.gameController.gamePlayground objectAtRow:currentRow-1 column:indexCol].value*2];
                            
                            [self.gameController.gamePlayground insertObject:temp atRow:currentRow-1 column:indexCol];
                            [self.gameController.gamePlayground insertObject:nil atRow:currentRow column:indexCol];
                            [self.gameController.gamePlayground objectAtRow:currentRow-1 column:indexCol].mergedThisRound = YES;
                            break;
                            
                        }
                        else {
                            [self.gameController.gamePlayground objectAtRow:currentRow-1 column:indexCol].mergedThisRound = YES;
                            hasChanged =NO;
                        }
                        
                    }
                    else {
                        hasChanged=YES;
                        Box* temp = [[Box alloc] initWithValue:[self.gameController.gamePlayground objectAtRow:currentRow     column:indexCol].value];
                        if(temp.value == 0) {
                            continue;
                        }
                        
                        [self.gameController.gamePlayground insertObject:temp atRow:currentRow-1 column:indexCol];
                        [self.gameController.gamePlayground insertObject:nil atRow:currentRow column:indexCol];
                    }
                }
            }
        }
        
        if(hasChanged){
            [self.gameController generateBoxAtRandomEmptyPlace];
        }
    }

    
    
    
    self.pointsLabel.text = [NSString stringWithFormat:@"%ld",[self.gameController points]];
    [self refreshBoxes];
}

-(void)refreshBoxes{
    NSString* imageName = [NSString string];
    
    
    
    
    
    for (UIImageView* boxImage in self.boxImageViews) {
        switch ([boxImage tag]) {
            case 0:
                imageName = [[self.gameController.gamePlayground objectAtRow:0 column:0] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 1:
                imageName = [[self.gameController.gamePlayground objectAtRow:0 column:1] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 2:
                imageName = [[self.gameController.gamePlayground objectAtRow:0 column:2] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 3:
                imageName = [[self.gameController.gamePlayground objectAtRow:0 column:3] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 4:
                imageName = [[self.gameController.gamePlayground objectAtRow:1 column:0] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 5:
                imageName = [[self.gameController.gamePlayground objectAtRow:1 column:1] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 6:
                imageName = [[self.gameController.gamePlayground objectAtRow:1 column:2] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 7:
                imageName = [[self.gameController.gamePlayground objectAtRow:1 column:3] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 8:
                imageName = [[self.gameController.gamePlayground objectAtRow:2 column:0] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 9:
                imageName = [[self.gameController.gamePlayground objectAtRow:2 column:1] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 10:
                imageName = [[self.gameController.gamePlayground objectAtRow:2 column:2] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 11:
                imageName = [[self.gameController.gamePlayground objectAtRow:2 column:3] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 12:
                imageName = [[self.gameController.gamePlayground objectAtRow:3 column:0] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 13:
                imageName = [[self.gameController.gamePlayground objectAtRow:3 column:1] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 14:
                imageName = [[self.gameController.gamePlayground objectAtRow:3 column:2] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
            case 15:
                imageName = [[self.gameController.gamePlayground objectAtRow:3 column:3] picture];
                boxImage.image =[UIImage imageNamed:imageName];
                break;
                
            default:
                break;
        }
    }

}


-(void)clearAllBoxes{
    [self.gameController removeAllPoints];
    for (NSUInteger row = 0; row < kMaxRows; row++) {
        for (NSUInteger col = 0; col < kMaxCols; col++) {
            [self.gameController.gamePlayground insertObject:nil atRow:row column:col];
        }
    }
    
    
    for (UIImageView* imageView in self.boxImageViews) {
        imageView.image = nil;
    }
}

-(void)generateRandomBackgroundPicture{
    NSUInteger randomPictureIndex = arc4random_uniform(kNumberOfPictures);
    NSString* pictureName = [NSString string];
    
    switch (randomPictureIndex) {
        case 0:
            pictureName = @"girl_1.png";
            break;
        case 1:
            pictureName = @"girl_2.png";
            break;
        case 2:
            pictureName = @"girl_3.png";
            break;
        case 3:
            pictureName = @"girl_4.png";
            break;
        case 4:
            pictureName = @"girl_5.png";
            break;
        case 5:
            pictureName = @"girl_6.png";
            break;
        case 6:
            pictureName = @"girl_7.png";
            break;
        case 7:
            pictureName = @"girl_8.png";
            break;
        case 8:
            pictureName = @"girl_9.png";
            break;
        case 9:
            pictureName = @"girl_10.png";
            break;
            
        default:
            break;
    }
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:pictureName]];
    self.gameBoard.backgroundColor = background;
}



@end
